﻿using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using __ts.Core.Utilities;
using System.Collections;

namespace CCU.Update
{
    static class Program
    {
        // Mutex
        static Mutex mutex = new Mutex(true, "{4b2c74d3-5ab4-47fd-b44e-cb17f120bba0}");

        /// <summary>
        /// Program entry point.
        /// </summary>
        /// <param name="args">flowId id[,id...]</param>
        private static void Main(string[] args)
        {
            if (!Util.IsRuningWithAdministrator())
            {
                MessageBox.Show("Must run with administrator.", "Error");
                return;
            }

            // No instances
            if (mutex.WaitOne(TimeSpan.Zero, true))
            {
                if (args != null && args.Length == 2)
                {
                    string flowId = args[0];
                    string[] idList = args[1].Split(',');
                    Dictionary<string, PackageInfo> pks = new Dictionary<string, PackageInfo>();
                    Packages _pks = new Packages(1, int.MaxValue);

                    foreach (string id in idList)
                    {
                        if (!string.IsNullOrEmpty(id) && _pks.ContainsKey(id))
                        {
                            pks.Add(id, _pks[id]);
                        }
                    }
                    IList<string> installeds = PackageExplorer.Installeds;
                    Dictionary<string, DownloadPackageInfo> downloadList = new Dictionary<string, DownloadPackageInfo>();
                    IDictionaryEnumerator enumerator = pks.GetEnumerator();
                    while (enumerator.MoveNext())
                    {
                        PackageInfo p = enumerator.Value as PackageInfo;
                        downloadList.Add(p.id, new DownloadPackageInfo()
                        {
                            id = p.id,
                            version = p.version,
                            description = p.description,
                            authors = p.authors,
                            size = p.size,
                            publishTime = p.publishTime,
                            md5 = p.md5,
                            installed = installeds.Contains(p.id),
                        });
                    }
                    update(flowId, downloadList, true);
                    return;
                }

                // Create main form
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                Application.Run(new PackageExplorer());

                // Release Mutex
                mutex.ReleaseMutex();

                // Disallow multiple istances
            }
            else
            {

                // Open previous instance
                NativeMethods.PostMessage((IntPtr)NativeMethods.HWND_BROADCAST, NativeMethods.WM_SHOWME, IntPtr.Zero, IntPtr.Zero);

            }

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="flowId"></param>
        /// <param name="downloadList"></param>
        /// <param name="autoRun"></param>
        internal static void update(string flowId, Dictionary<string, DownloadPackageInfo> downloadList, bool autoRun = false)
        {
            UrlDownloader dl = new UrlDownloader(flowId, autoRun, downloadList);
            dl.ShowDialog();
            if (dl.downloadOk)
            {
                Installer stl = new Installer(dl.pks);
                stl.ShowDialog();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        internal class NativeMethods
        {
            public const int HWND_BROADCAST = 0xffff;
            public static readonly int WM_SHOWME = RegisterWindowMessage("WM_SHOWME");
            [DllImport("user32")]
            public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);
            [DllImport("user32")]
            public static extern int RegisterWindowMessage(string message);
            [DllImportAttribute("user32.dll")]
            public static extern bool SetForegroundWindow(IntPtr hWnd);
        }

        //private static Packages pks;

        //[STAThread]
        //static void Main(string[] args)
        //{
        //    // 参数格式：packageId,flowId
        //    string[] inputs = args.Length > 0 ? args[0].Split(',') : new string[2];
        //    // 是否自动执行
        //    bool autorun;

        //    if (string.IsNullOrEmpty(inputs[0]))
        //        autorun = false;
        //    else
        //        autorun = true;

        //    // 获取package列表
        //    pks = new Packages();

        //    if (pks.Count < 1)
        //    {
        //        if (autorun == false)
        //            MessageBox.Show("can't get package list from server.\r\n" + pks.errorInfo);
        //        return;
        //    }

        //    // 没有参数，需要手动操作
        //    if (autorun == false)
        //    {
        //        // 显示package列表
        //        SelectPackage sp = new SelectPackage(pks);
        //        sp.ShowDialog();

        //        if (string.IsNullOrEmpty(sp.SelectItemKey))
        //            return;

        //        inputs[0] = sp.SelectItemKey;
        //        inputs[1] = "_" + Guid.NewGuid().ToString();
        //    }

        //    // 根据packageId，从服务器下载更新包
        //    PackageInfo package = pks[inputs[0]];
        //    if (package == null)
        //    {
        //        if (autorun == false)
        //            MessageBox.Show("can't find package in package list.");
        //        return;
        //    }

        //    // 是否自动执行
        //    package.AutoRun = autorun;
        //    // 从服务器下载更新包
        //    bool flag = package.Download(inputs[1]);
        //    SetupPackage setup = new SetupPackage(package);

        //    // 写下载的日志
        //    setup.WriteLog(package.LogBuilder.ToString());
        //    package.LogBuilder.Length = 0;

        //    // 执行更新包
        //    if (flag)
        //    {
        //        setup.ShowDialog();
        //        // 写更新的日志
        //        setup.WriteLog(package.LogBuilder.ToString());
        //    }

        //    // 传送日志

        //}
    }
}
